package com.lagou.edu.service.impl;

import com.lagou.edu.dao.entity.AuthCode;
import com.lagou.edu.dao.repository.AuthCodeRepository;
import com.lagou.edu.service.SendService;
import com.lagou.edu.service.VerificationService;
import com.lagou.edu.util.CaptchaUtil;
import org.apache.dubbo.config.annotation.Reference;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Objects;

/**
 * @author bobcheng
 * @date 2020/7/12
 */
@Service
@org.apache.dubbo.config.annotation.Service
public class VerificationServiceImpl implements VerificationService {

    @Reference
    private SendService sendService;
    @Autowired
    private AuthCodeRepository authCodeRepository;

    @Override
    public boolean createAndSend(String email) {
        String code = CaptchaUtil.genCode(6);
        DateTime now = DateTime.now();
        Date createTime = now.toDate();
        Date expireTime = now.plusMinutes(10).toDate();
        AuthCode authCode = AuthCode.builder()
                .email(email)
                .code(code)
                .createtime(createTime)
                .expiretime(expireTime)
                .build();
        authCodeRepository.save(authCode);
        return sendService.sendCaptcha(email, code);
//        return true;
    }

    @Override
    public int validate(String email, String code) {
        AuthCode authCode = authCodeRepository.findTopByEmailOrderByCreatetimeDesc(email);
        if (Objects.isNull(authCode) || !Objects.equals(authCode.getCode(), code)) {
            return 1;
        }
        return DateTime.now().toDate().before(authCode.getExpiretime()) ? 0 : 2;
    }
}
